package com.up.upzl.base.config;

import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.PasswordEncoder;

import com.up.upzl.biz.service.UserService;
import com.up.upzl.biz.service.impl.CustomerUserServiceImpl;
import com.up.upzl.filter.JWTAuthenticationFilter;
import com.up.upzl.filter.JWTLoginFilter;

@Configuration
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

	private CustomerUserServiceImpl userDetailsService;

	private UserService userService;

	public WebSecurityConfig(CustomerUserServiceImpl userDetailsService, UserService userService) {
		this.userDetailsService = userDetailsService;
		this.userService = userService;
	}

	@Override
	public void configure(WebSecurity web) throws Exception {
		// 每一个请求对应一个空的filter链,这里一般不要配置过多,
		// 因为查找处是一个for循环,过多就导致每个请求都需要循环一遍直到找到
		// web.ignoring().antMatchers("/", "/login", "/favicon.ico");
	}

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.cors().and().csrf().disable().authorizeRequests().anyRequest().permitAll().and()
				.addFilter(new JWTAuthenticationFilter(authenticationManager()))
				.addFilter(new JWTLoginFilter(authenticationManager(), userService));
	}

	@Override
	public void configure(AuthenticationManagerBuilder auth) throws Exception {

		auth.userDetailsService(userDetailsService).passwordEncoder(new PasswordEncoder() {
			@Override
			public boolean matches(CharSequence rawPassword, String encodedPassword) {
				return rawPassword.equals(encodedPassword);
			}

			@Override
			public String encode(CharSequence rawPassword) {
				return null;
			}
		});
	}

}
